<template>
  <div style="margin:0 200px;padding: 50px;background-color: #FFFFFF">
    <div style="display:flex;">
      <div>
        <h1 style="margin-bottom: 10px">发布职位</h1>
        完整的职位信息，有助于为你匹配精准的人才（注意：<span>*</span>为必填内容）
      </div>
      <div style="display: flex;align-items: center;margin-left: auto">
        <el-button plain size="large" type="primary" @click="uploadJob">
          <el-icon>
            <UploadFilled/>
          </el-icon>
          上传职位
        </el-button>
      </div>
    </div>

    <el-form
        :model="form"
        label-width="auto"
        style="max-width: 1000px;margin-top: 30px"
    >
      <!-- 职位名称 -->
      <el-form-item>
        <template #label>
          <span>*</span>职位名称
        </template>
        <el-input v-model="form.jobName"/>
      </el-form-item>
      <!-- 职位类型 -->
      <el-form-item>
        <template #label>
          <span>*</span>职位类型
        </template>
        <el-input v-model="form.jobTypeName" placeholder="选择一个职位类型" disabled>
          <template #suffix>
            <el-icon @click="openDialog">
              <calendar/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <!-- 薪资 -->
      <el-form-item style="display: flex">
        <template #label>
          <span>*</span>薪资
        </template>
        <el-col :span="11" style="display: flex">
          <el-input v-model="form.min_salary" :min="0" :step="1" placeholder="请输入整数" type="number"
                    @input="updateMinSalary"/>
          &nbsp&nbspk
        </el-col>
        <el-col :span="2" class="text-center" style="display: flex; justify-content: center; align-items: center;">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="11" style="display:flex;">
          <el-input v-model="form.max_salary" :min="0" :step="1" placeholder="请输入整数" type="number"
                    @input="updateMaxSalary"/>
          &nbsp&nbspk
        </el-col>
      </el-form-item>
      <!-- 年龄 -->
      <el-form-item>
        <template #label>
          <span>*</span>年龄
        </template>
        <el-input v-model="form.ageRequire" placeholder="请输入年龄限制"/>
      </el-form-item>
      <!-- 工作经验 -->
      <el-form-item>
        <template #label>
          <span>*</span>工作经验
        </template>
        <el-select v-model="form.experienceRequire" placeholder="请选择工作经验要求">
          <el-option label="经验不限" value="经验不限"/>
          <el-option label="1年以下" value="1年以下"/>
          <el-option label="1-3年" value="1-3年"/>
          <el-option label="3-5年" value="3-5年"/>
          <el-option label="5-10年" value="5-10年"/>
          <el-option label="10年以上" value="10年以上"/>
        </el-select>
      </el-form-item>
      <!-- 技能要求 -->
      <el-form-item v-model="form.skillRequire">
        <template #label>
          <span>*</span>技能要求
        </template>
        <!-- 已选中标签 -->
        <el-tag v-for="(skill,index) in form.skillRequire" :key="index" :disable-transitions="false" closable
                @close="handleClose(skill)">
          {{ skill }}
        </el-tag>
        <!-- 点击后的弹窗 -->
        <el-popover
            v-model:visible="popoverVisible"
            placement="top"
            title="请选择一个技能"
            trigger="manual"
            width="200"
        >
          <template #reference>
            <!-- 点击添加按钮 -->
            <el-button plain size="small" @click="showPopover">+ 技能</el-button>
          </template>
          <!-- 弹窗内可选技能 -->
          <el-button
              v-for="skill in skill_types"
              :key="skill.id"
              @click="addSkill(skill)"
              style="margin: 5px"
              size="small"
              type="primary"
              plain
          >{{ skill.skillName }}
          </el-button>
        </el-popover>
      </el-form-item>
      <!-- 学历要求 -->
      <el-form-item>
        <template #label>
          <span>*</span>学历要求
        </template>
        <el-select v-model="form.educationRequire" placeholder="请选择学历要求">
          <el-option label="不限" value="不限"/>
          <el-option label="大专" value="大专"/>
          <el-option label="本科" value="本科"/>
          <el-option label="硕士" value="硕士"/>
          <el-option label="博士" value="博士"/>
          <el-option label="中专/中技" value="中专/中技"/>
        </el-select>
      </el-form-item>
      <!-- 职位介绍 -->
      <el-form-item label="职位介绍">
        <el-input v-model="form.jobIntroduce" type="textarea" :autosize="{ minRows: 10}"/>
      </el-form-item>
      <!-- 确认 & 取消操作 -->
      <el-form-item style="float: right">
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 选择标签表单 -->
  <el-dialog v-model="dialogFormVisibel" title="选择职位类型">
    <el-input placeholder="在此搜索" v-model="searchJobType" @input="handleSearchJobType"></el-input>
    <el-scrollbar wrap-class="scrollbar-wrapper" style="height: 300px;">
      <div class="button-list">
        <el-button v-for="item in job_types" :key="item.jobTypeId" plain round style="margin-top: 20px"
                   type="primary" @click="selectJobType(item)">
          {{ item.jobTypeName }}
        </el-button>
      </div>
    </el-scrollbar>
  </el-dialog>
  <!-- 文件上传职位 -->
  <el-dialog
      v-model="dialogVisible"
      :before-close="handleCloseUp"
      width="500"
  >
    <el-upload
        ref="uploadRef"
        :accept="'.pdf,.doc,.docx,.xlsx,.xls'"
        :auto-upload="false"
        :limit="1"
        :onSuccess="handleSuccess"
        action="http://localhost:60000/company/api/v1/upload"
        class="upload-demo"
        drag
    >
      <div class="el-upload__text">
        <el-text size="large" style="color: #6b778c">拖拽文件到这里</el-text>
      </div>
      <div style="margin-top: 20px">
        <el-text style="color: #6b778c">建议使用 PDF 文件，也支持DOC、DOCX、XLS、XLSX 格式</el-text>
      </div>
      <div style="margin-top: 10px">
        <el-text style="color: #f26d49">文件大小不超过20M</el-text>
      </div>
      <el-button style="margin-top: 30px" type="primary">
        上传职位
      </el-button>
    </el-upload>
    <div style="display: flex; margin-top: 20px">
      <div style="flex-grow: 2"></div>
      <el-button type="info" @click="handleCloseUp">
        取消
      </el-button>
      <div style="flex-grow: 1"></div>
      <el-button type="success" @click="queding">
        确定
      </el-button>
      <div style="flex-grow: 2"></div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import {useRoute, useRouter} from "vue-router";
import {Action, ElMessageBox, ElMessage} from "element-plus";
import {recruiterApi} from "../../api/app.js";
// import {debounce} from '../../router/debounce';
import {debounce} from 'lodash/function';

const router = useRouter();
const route = useRoute();
const isNew = ref(true); // 是否是发布职业 1.true发布职业 2.false修改已有职位信息
// 表单信息
const form = ref({
  id: 0,
  jobName: "",
  jobTypeId: 0,
  jobTypeName: "",
  jobIntroduce: "",
  min_salary: 0,
  max_salary: 0,
  salary: "",
  skillRequire: [],
  educationRequire: "",
  experienceRequire: "",
  ageRequire: "",
  postTime: "",
})
// 招聘者信息
const recruiter = ref({
  // 必要的
  id: 0,
  hrNick: "",
  status: "",
  phone: "",
  companyName: "",
  companyType: "",
  companyBoss: "",
  companyIntroduce: "",
  companyAddress: "",
  companyImage: "",
  // 不必要的
  gender: "",
  birth: "",
  lastOnline: "",
  email: "",
  address: "",
  headImage: "",
  name: "",
  password: "",
})
// 职位类型信息
const job_types = ref([]);
const searchJobType = ref('');
// 技能类型信息
const skill_types = ref([]);

// 删除已选技能标签
const handleClose = (tag: string) => {
  form.value.skillRequire.splice(form.value.skillRequire.indexOf(tag), 1);
}
const popoverVisible = ref(false);
// 是否需要填写
const showPopover = () => {
  popoverVisible.value = true;
}
// 点击添加
const addSkill = (skill) => {
  if (form.value.skillRequire.indexOf(skill.skillName) == -1) {
    form.value.skillRequire.push(skill.skillName);
    popoverVisible.value = false;
  } else {
    ElMessage({type: "error", message: "已存在，请勿重复添加！"});
  }
}

// 初始化
onMounted(() => {
  getJobType(); // 获取职业类型
  recruiter.value = JSON.parse(localStorage.getItem('recruiter')); // 获取当前用户信息

  console.log("当前路径：" + route.path)
  // console.log("route的参数："+JSON.stringify(route.query, null, 2))

  // 如果是修改原有职位信息，接收原有消息
  if (route.query && JSON.stringify(route.query, null, 2) !== '{}') {
    console.log(Object.assign(form.value, route.query));
    console.log("进来了！！！！参数：", route.query)
    const reg_salary = /(\d+(?:\.\d+)?)k-(\d+(?:\.\d+)?)k/; // 薪资正则
    // 将薪资转换成最大最小薪资用于显示
    const match = form.value.salary.match(reg_salary);
    if (match) {
      form.value.min_salary = parseFloat(match[0]);
      form.value.max_salary = parseFloat(match[2]);
    }
    isNew.value = false;
  }
});

// 获取职业类型
const getJobType = () => {
  recruiterApi.getAllJobType({
    size: 99,
    page: 1
  }).then(response => {
    job_types.value = response.data;
  }).catch(error => {
    console.error(error);
  })
}

const dialogFormVisibel = ref(false);
// 打开选择职业类型表单
const openDialog = () => {
  dialogFormVisibel.value = true;
}
// 选择职业类型
const selectJobType = (item) => {
  // 选择职位类型
  form.value.jobTypeName = item.jobTypeName;
  form.value.jobTypeId = item.jobTypeId;
  // 获取其全部技能类型
  recruiterApi.getSkillsByJobTypeId({
    jobTypeId: form.value.jobTypeId
  }).then(response => {
    skill_types.value = response.data;
  }).catch(error => {
    console.error(error);
  });
  dialogFormVisibel.value = false;
}
// 处理搜索职业类型
const handleSearchJobType = debounce((val) => {
  if (val.length > 0) { // 输入框内有输入
    console.log("请求后端1次")
    recruiterApi.searchJobTypeByName({
      size: 99,
      page: 1,
      name: val
    }).then(response => {
      job_types.value = response.data;
    }).catch(error => {
      console.error(error);
    })
  } else { // 无输入，还原全部数据
    getJobType();
  }
},1000)

// 处理输入数字转为int
const updateMaxSalary = (value) => {
  form.value.max_salary = parseInt(value);
}

const updateMinSalary = (value) => {
  form.value.min_salary = parseInt(value);
}

// 确定
const onSubmit = () => {
  // 必填选项为空
  if (form.value.jobTypeName == "" || form.value.jobName == "" || form.value.min_salary == "" || form.value.max_salary == "" || form.value.experienceRequire == "" || form.value.educationRequire == "" || form.value.skillRequire == []) {
    ElMessageBox.alert('必填选项不得为空！', '操作失败', {
      confirmButtonText: 'OK',
      callback: (action: Action) => {
        ElMessage({
          type: 'error',
          message: `操作失败`,
        })
      },
    });
  } else if (form.value.max_salary < form.value.min_salary) { // 最高工资低于最低工资
    ElMessageBox.alert('工资上限不能低于下限！', '操作失败', {
      confirmButtonText: 'OK',
      callback: (action: Action) => {
        ElMessage({
          type: 'error',
          message: `操作失败`,
        })
      },
    });
  } else {
    form.value.salary = `${form.value.min_salary}k-${form.value.max_salary}k`;
    console.log("是否是发布新职位：", isNew)
    if (isNew.value) { // 发布新职位
      recruiterApi.addJob({
        jobName: form.value.jobName,
        jobTypeId: form.value.jobTypeId,
        jobTypeName: form.value.jobTypeName,
        jobIntroduce: form.value.jobIntroduce,
        salary: form.value.salary,
        skillRequire: form.value.skillRequire,
        educationRequire: form.value.educationRequire,
        experienceRequire: form.value.experienceRequire,
        ageRequire: form.value.ageRequire,
        hrId: recruiter.value.id,
        hrName: recruiter.value.hrNick,
        status: recruiter.value.status,
        phone: recruiter.value.phone,
        companyName: recruiter.value.companyName,
        companyType: recruiter.value.companyType,
        companyBoss: recruiter.value.companyBoss,
        companyIntroduce: recruiter.value.companyIntroduce,
        companyAddress: recruiter.value.companyAddress,
        companyImage: recruiter.value.companyImage,
      }).then(response => {
        //console.log(response);
        ElMessage({
          message: '发布成功！',
          type: 'success',
        });
        router.back();
        // router.push({path: '/recruiterMain/selfManage/jobMessage'});
      }).catch(error => {
        console.log(error);
      })
    } else { // 修改旧职位
      console.log("修改--------")
      recruiterApi.editJob({
        id: form.value.id,
        jobName: form.value.jobName,
        jobTypeId: form.value.jobTypeId,
        jobTypeName: form.value.jobTypeName,
        jobIntroduce: form.value.jobIntroduce,
        salary: form.value.salary,
        skillRequire: form.value.skillRequire,
        educationRequire: form.value.educationRequire,
        experienceRequire: form.value.experienceRequire,
        ageRequire: form.value.ageRequire,
        hrId: recruiter.value.id,
        hrName: recruiter.value.hrNick,
        status: recruiter.value.status,
        phone: recruiter.value.phone,
        companyName: recruiter.value.companyName,
        companyType: recruiter.value.companyType,
        companyBoss: recruiter.value.companyBoss,
        companyIntroduce: recruiter.value.companyIntroduce,
        companyAddress: recruiter.value.companyAddress,
        companyImage: recruiter.value.companyImage,
        postTime: form.value.postTime
      }).then(response => {
        //console.log(response);
        ElMessage({
          message: '修改成功！',
          type: 'success',
        });
      }).catch(error => {
        console.log(error);
      });
      router.back();
    }
  }
}

// 取消
const onCancel = () => {
  router.back();
}


const dialogVisible = ref(false)
const uploadRef = ref(null)
// 上传职位
const uploadJob = () => {
  dialogVisible.value = true
}

const handleSuccess = (response, file) => {
  console.log(response)
  ElMessageBox.alert('上传成功', '提示', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: 'OK',
    callback: (action) => {
      dialogVisible.value = false;
      router.back()
    },
  })
}
const handleCloseUp = () => {
  dialogVisible.value = false
  onMounted(null)
}
const queding = () => {
  // 保存
  console.log(uploadRef.value)
  if (uploadRef.value) {
    console.log(uploadRef.value)
    // console.log('0000')
    uploadRef.value.submit()
  } else {
    dialogVisible.value = false;
    ElMessage({
      type: 'info',
      message: '简历上传失败'
    })
  }

}
</script>

<style scoped>
span {
  color: red;
  margin-right: 5px;
}
</style>
